<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use App\Http\Requests\AdminLoginPostRequest;
use App\Http\Requests\HomeLoginPostRequest;
use App\Http\Requests;

use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
class LoginController extends Controller
{
	/*
		显示后台登录页面
	*/
	public function getLogin()
	{	 
		
		//显示模板
		return view('admin.login.login');
		
	}

	/*
		后台登录验证
	*/
	
	public function postCheck(AdminLoginPostRequest $request)
    {
         // dd($request->all());
        // dd($request->only('username'));

       $user = DB::table('user')->where('username',$request->input('username'))->first();
		// dd($user);
        // dd($user->only('password'));
      //检测密码是否一致
       // dd($user);
       
       if(!$user){
       		return back()->with('error','用户名或密码错误');
       }else{
       		$qx = $user->qx;
       		if($qx != 3){
		       	if(Hash::check($request->input('password'),$user->password)) {
		        	//登录成功
		        	
		        	session(['hid'=>$user->id]);
		        	//跳转到后台首页
		        	 return redirect('/admin')->with('success','欢迎'.$user->username.'登录');
		        }else{
		        	return back()->with('error','用户名或密码错误');
		        }
		    }else{
		    	return back()->with('error','你没有权限');
		    }
    	}
    }
	public function getLogout(){
			// echo '222';
		session()->forget('id');
		return redirect('/admin');
	}
	
	


	// //前台登录
	public function login()
	{
		if(!array_key_exists('HTTP_REFERER',$_SERVER)){
			$url = '/';
		}else{
			//获取上级url
			$url = $_SERVER['HTTP_REFERER'];
		}
		//显示登录页面
		return view(' home.login.login',['url'=>$url]);
	}
	//退出登录
	public function getClear()
	{
		//显示登录页面
		session()->forget('id');
		session()->forget('per_pic');

		if(!array_key_exists('HTTP_REFERER',$_SERVER)){
			$url = '/';
		}else{
			//获取上级url
			$url = $_SERVER['HTTP_REFERER'];
		}

		return redirect($url);
	}
	/*
		前台登录验证
	*/
	
	public function jian(Request $request)
    {
         // dd($request->all());
        // dd($request->only('password'));

       $user = DB::table('user')->where('username',$request->input('username'))->first();

		// dd($pic);

		// dd($user);
       if(!$user){
	    	return back()->with('error','用户名或密码错误');
	    }
		$pic = $user->pic;




		session(['per_pic'=>$pic]);
        

	      //检测密码是否一致
	       if(Hash::check($request->input('password'),$user->password)) {
	        	//登录成功
	        	session(['id'=>$user->id]);
	        	session(['username'=>$user->username]);
	        	$status = DB::table('user')->where('id',session('id'))->first();
	        	// dd($status);
	        	if($status->status == 2){
	        		//接收上级url
	        		$url = $request->input('url');
	        	 	return redirect($url)->with('success','欢迎'.$user->username.'登录');	
	        	}else{
	        	return back()->with('error','您还没有激活账号');	
	        	}
	        }else{
	        	return back()->with('error','用户名或密码错误');
	        }
	 
			//后台退出 
    }
}  
